//
//  StatusCell.swift
//  weibopush
//
//  Created by 龚欣 on 15/6/30.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit
import SDWebImage
import FFAutoLayout
import SVProgressHUD

let PictureViewReuseIdentifier = "PictureViewReuseIdentifier"

protocol statusCellDelegate : NSObjectProtocol{

    func statusCellImageDidClick(cell : StatusCell,index : Int)
}

class StatusCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate {

   weak var photoDelegate : statusCellDelegate?
    
    var status : Status? {
        didSet{

            iconView.sd_setImageWithURL(NSURL(string: status!.user!.profile_image_url!))
            nameLabel.text = status?.user?.name
            vipView.image = status?.user?.mbrankImage
            verifiedIcon.image = status?.user?.verified_type_image
            timeLabel.text = NSDate().sinaDateWithString((status?.created_at)!).dateDescription()
            sourceLabel.text = status?.sourceText
            contentLabel.attributedText =  EmoticonPackage.emoticonAttributeStringWithString(status?.text ?? "", font: contentLabel.font!)

            let result = calcutePictureViewSize()
            heightConstraint?.constant = result.viewSize.height
            widthConstraint?.constant = result.viewSize.width
            layout.itemSize = result.itemSize
            //这里面才是拿到数据的地方，拿到数据刷新！！注意这里
            
            pictureView.reloadData()
            
            if status?.retweeted_status != nil{
                let text = "\(status!.retweeted_status!.user!.name! ) : \(status!.retweeted_status!.text!)"
                
                tweetStatusLabel.attributedText = EmoticonPackage.emoticonAttributeStringWithString(text, font: tweetStatusLabel.font)
            }
        }
    
        
    }
    
   override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        let screenW = UIScreen.mainScreen().bounds.width
    
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.60, alpha: 1.0)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenW, height: 8))
    
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(vipView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(verifiedIcon)
        addSubview(contentLabel)
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 12
        addSubview(pictureView)
        preparePictureView()
        addSubview(footerView)

    
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 35, height: 35), offset: CGPoint(x: 12, y: 20))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        vipView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 6, y: 0))
        timeLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: nameLabel, size: nil, offset: CGPoint(x: 0, y: 4))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 4, y: 0))
        verifiedIcon.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 4, y: 4))
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))
    
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenW, height: 30), offset: CGPoint(x: -12, y: 12))
    
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //防止imageURLS是nil会崩的情况
        return status?.pictureURLS?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureViewReuseIdentifier, forIndexPath: indexPath) as! PictureViewCell
        cell.imageURL = status?.pictureURLS![indexPath.item]
        
        return cell
        
    }
    // MARK: 注意这里要使用cell进行转换，而不是使用cell.iconView进行坐标转换。注意！！！！！
    func screenFrame(imageIndex : Int) -> CGRect{
        let indexPath = NSIndexPath(forItem: imageIndex, inSection: 0)
        let cell = pictureView.cellForItemAtIndexPath(indexPath) as! PictureViewCell
       return pictureView.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
    }
    // MARK: 通过之前已经缓存的图片返回图片modal之后的全屏大小
    func fullScreenFrame(imageIndex : Int) -> CGRect {
        let screenW = UIScreen.mainScreen().bounds.size.width
        let screenH = UIScreen.mainScreen().bounds.size.height
        let url = status?.pictureURLS![imageIndex]
        
        if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url?.absoluteString){
        
            let scale = image.size.height / image.size.width
            let h = scale * screenW
            if h > screenH {
                return CGRect(x: 0, y: 0, width: screenW, height: h)
            }
            return CGRect(x: 0, y: (screenH - h) * 0.5, width: screenW, height: h)
        }
        return CGRectZero
//        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url?.absoluteString)
    }
    
    ///  选中图片缓存大图，并显示动画，缓存完后调用代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let url = status!.largePicURLS![indexPath.item]
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PictureViewCell
        
        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: { (bytes, totalBytes) -> Void in
            
            let progress = CGFloat(bytes) / CGFloat(totalBytes)
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                cell.iconView.progress = progress
            })
            
            }) { [unowned self](image, error, _, _, _) -> Void in
                if image != nil{
                    self.photoDelegate?.statusCellImageDidClick(self, index: indexPath.item)
                    return
                }
                if error != nil{
                    cell.iconView.progress = 0
                    print(error)
                    return
                }
        }

    }
    
    
    // MARK: 图片视图的属性设置,数据源，代理设置
    func preparePictureView(){
        pictureView.dataSource = self
        pictureView.delegate = self
        pictureView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        pictureView.registerClass(PictureViewCell.self, forCellWithReuseIdentifier: PictureViewReuseIdentifier)
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
    }
    // MARK: 设置cell高度。
    func rowHeight(cellStatus : Status) -> CGFloat{
        //把数据传进去 只有拿到数据了才能正确的设置布局
        status = cellStatus
        layoutIfNeeded()
        return CGRectGetMaxY(footerView.frame)
    }
    // MARK: 记录约束 为后面根据图片的个数调整约束大小做准备
    func recordPictureCons(cons : [NSLayoutConstraint]){
        
        widthConstraint = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heightConstraint = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
   // MARK: 通过模型返回cell的标示符
   class func reuserIdentifierForCell(status : Status) -> String{
        return status.retweeted_status == nil ? statusNormalReuserCellIdentifier : statusForwardReuserCellIdentifier
   
    }
    
    // MARK: 计算图片视图内部图片的布置
    func calcutePictureViewSize() -> (viewSize : CGSize,itemSize : CGSize){
        //-----------------------------------------------
        //这里的疑惑  能不能直接写成 status?.imageURLS?.count
        let imageCount = status?.pictureURLS?.count ?? 0
        let itemSize = CGSize(width: 90, height: 90)
        let margin : CGFloat = 10
        //没有图片，直接返回0
        if imageCount == 0{
            return (CGSizeZero,itemSize)
        }
        
        //一张图保持原图的尺寸
        if imageCount == 1{
            let key = status?.pictureURLS![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            if (image != nil){
                return (image.size,image.size)
            }
            return (CGSizeZero,itemSize)
        }
        
        //4张图片 2*2排列
        if imageCount == 4{
            return (CGSize(width: itemSize.width * 2 + margin, height: itemSize.height * 2 + margin),itemSize)
        }
        
        let rowCount  = (imageCount - 1)/3 + 1
        let w = 3 * itemSize.width + 2 * margin
        let h = CGFloat(rowCount) * itemSize.height + (CGFloat(rowCount) - 1 )*margin
        
        return (CGSize(width: w, height: h),itemSize)
    }
    
    
    // MARK: 懒加载控件
    lazy var iconView = UIImageView()
   
    var nameLabel = UILabel(color: UIColor.darkGrayColor(), fonSize: 14, hasLines: false)
    
    lazy var vipView : UIImageView = UIImageView()
  
    lazy var timeLabel = UILabel(color: UIColor.orangeColor(), fonSize: 10)
    
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fonSize: 10)
    
    lazy var verifiedIcon = UIImageView()
    
    lazy var contentLabel = UILabel(color: UIColor.darkGrayColor(), fonSize: 15, hasLines: true)
    
    lazy var layout = UICollectionViewFlowLayout()
    lazy var pictureView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    
    lazy var footerView : StatusFooterView = StatusFooterView()

    lazy var tweetStatusLabel = UILabel(color: UIColor.darkGrayColor(), fonSize: 14, hasLines: true)
    
    /// 配图视图宽度的约束
    private var widthConstraint : NSLayoutConstraint?
    /// 配图视图高度的约束
    private var heightConstraint : NSLayoutConstraint?
}


class PictureViewCell : UICollectionViewCell {
    
    var imageURL : NSURL?{
        didSet{
            iconView.sd_setImageWithURL(imageURL)

          gifTipView.hidden = (imageURL?.absoluteString.pathExtension.lowercaseString != "gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(iconView)
        addSubview(gifTipView)
        iconView.ff_Fill(self)
        gifTipView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil)
        //修改图片格式为ScaleAspectFill。这个模式可以等比例缩放原图，不会拉伸。但是记得要剪切多出的部分
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
        
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var iconView : GXImageView = GXImageView()
    lazy var gifTipView : UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}


/// MARK: 自定义底部视图
class StatusFooterView : UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        backgroundColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 1.0)
        ff_HorizontalTile([forwardBtn,commentBtn,likeBtn], insets: UIEdgeInsetsZero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var forwardBtn : UIButton = UIButton(title: "转发", color: UIColor.darkGrayColor(), fontSize: 12, imageName: "timeline_icon_retweet")
    lazy var commentBtn : UIButton = UIButton(title: "评论", color: UIColor.darkGrayColor(), fontSize: 12, imageName: "timeline_icon_comment")
    lazy var likeBtn : UIButton = UIButton(title: "赞", color: UIColor.darkGrayColor(), fontSize: 12, imageName: "timeline_icon_like")

    
}
